/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.authstr.auth.interceptor;

import com.authstr.auth.jwt.JwtUtil;
import com.authstr.auth.jwt.ShiroJwtToken;
import com.authstr.auth.service.imip.UserAuthServiceImpl;
import com.authstr.auth.service.inter.UserAuthService;
import com.authstr.basic.reqres.utils.WebUtils;
import com.authstr.model.base.BaseUser;
import org.apache.shiro.ShiroException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 进行用户的访问过滤
 * 通过继承AccessControlFilter的进行实现
 * https://www.cnblogs.com/CESC4/p/7599927.html
 * 抽象方法功能:
 * isAccessAllowed：表示是否允许访问；mappedValue就是[urls]配置中拦截器参数部分，如果允许访问返回true，否则false；
 * onAccessDenied：表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，将直接返回即可。
 *
 * 父类提供的方法:
 * void setLoginUrl(String loginUrl) //身份验证时使用，默认/login.jsp
 * String getLoginUrl()
 * Subject getSubject(ServletRequest request, ServletResponse response) //获取Subject实例
 * boolean isLoginRequest(ServletRequest request, ServletResponse response)//当前请求是否是登录请求
 * void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException //将当前请求保存起来并重定向到登录页面
 * void saveRequest(ServletRequest request) //将请求保存起来，如登录成功后再重定向回该请求
 * void redirectToLogin(ServletRequest request, ServletResponse response) //重定向到登录页面
 */
public class ShiroJwtFilter extends AccessControlFilter {


    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest =  (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            //获取请求头的token
            String token = JwtUtil.cookieAndHeaderGetToken(httpServletRequest);
            Subject subject = getSubject(request, response);
            if(StringUtils.hasText(token)){
                //使用token进行shiro认证
                try {
                    subject.login(new ShiroJwtToken(token));
                }catch (ShiroException e){
                    httpServletRequest.setAttribute("tips", "认证失效");
                    return false;
                }
                //判断是否应该刷新token
                if(JwtUtil.isRefreshToken(token)){
                    try {
                        UserAuthService shiroFactory = UserAuthServiceImpl.me();
                        String account = JwtUtil.getAccount(token);
                        BaseUser user = shiroFactory.user(account);
                        String newToken = JwtUtil.sign(user.getAccount(), user.getPassword());
                        JwtUtil.cookieAndHeaderSetToken(WebUtils.getResponse(),newToken);
                    }catch (Exception e){
                        e.printStackTrace();
                        //日志 刷新token出错
                    }
                }else{
                    //不刷新,将token重新放回响应头
                    httpServletResponse.setHeader("token",token);
                }
            }else{
                return false;
            }

            return true;
        }
    }

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest =  (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        /**
         * 如果是ajax请求则不进行跳转
         */
        if (httpServletRequest.getHeader("x-requested-with") != null
                && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            return false;
        } else {
            System.out.println(getLoginUrl());
            httpServletResponse.sendRedirect(getLoginUrl());
//            saveRequestAndRedirectToLogin(request, response);
        }
        return false;
    }
}
